﻿Imports DataLayer
Imports Negocio
Imports Servicios
Imports System.Configuration
Imports Excepciones
Imports System.Xml.Serialization

Public Class InitApp
    Public Shared Sub Init()

        'Inicializando------------

        'Carga idioma por default-------
        Dim i As New Idioma()
        Current.Idioma = i
        Try

            Current.Idioma = GesIdiomas.Deserialize(ConfigurationManager.AppSettings("language"))

        Catch ex As Exception
            Throw New LanguageFileNotFoundException()
        End Try

        TestDB()


    End Sub


    Public Shared Sub TestDB()

        'Carga la cadena de conexion al repositorio
        Try
            RepositoryFactory.ConnectionString = ConfigurationManager.ConnectionStrings("conn").ToString()
        Catch ex As Exception
            Throw New ConnectionStringNotFoundException()
        End Try

        Try
            'Test Conexion a DB
            Dim repo As IRepository = RepositoryFactory.Create()
            repo.Conectar()
            repo.Desconectar()
            repo.Dispose()
            repo = Nothing
        Catch ex As CannotOpenConnectionDataBaseException
            'Throw New CannotOpenConnectionDataBaseException()
            If MessageExt.Show(GesIdiomas.TraduceMensaje("MSGDAO001").ToString, MessageBoxButtons.YesNo) = MsgBoxResult.Yes Then
                If ConnectionDialog() = True Then
                    TestDB()
                Else
                    Throw New CannotOpenConnectionDataBaseException()
                End If
            Else
                Throw New CannotOpenConnectionDataBaseException()
            End If
        End Try
    End Sub


    Public Shared Function ConnectionDialog() As Boolean

        Dim config As Configuration = ConfigurationManager.OpenExeConfiguration("SIPRO.exe")
        Dim dialog As New frmSQLConnectionDialog()
        dialog.ConnectionString = config.ConnectionStrings.ConnectionStrings("conn").ConnectionString
        If dialog.ShowDialog = Windows.Forms.DialogResult.Cancel Then Return False

        Dim CS As String = dialog.ConnectionString


        'Dim config As Configuration = ConfigurationManager.OpenExeConfiguration("SIPRO.exe")
        config.ConnectionStrings.ConnectionStrings("conn").ConnectionString = CS
        config.Save(ConfigurationSaveMode.Modified)

        ConfigurationManager.RefreshSection("connectionStrings")
        Return True
    End Function

End Class
